import React, { useRef, useState, useEffect } from "react";
import { Modal, Spin, Tree, Upload, Empty, Button, Tooltip, Radio } from "antd";
import { LeftOutlined, RightOutlined, EditOutlined, UnorderedListOutlined, AppstoreOutlined, DragOutlined, DeleteOutlined, ArrowDownOutlined, ShareAltOutlined, QuestionCircleOutlined, DesktopOutlined } from "@ant-design/icons";
import styled from "styled-components";
import { useNavigate } from "react-router-dom";
import * as antdHelper from "../../utils/antd-helper";
import store from "../../utils/store";
import * as oss from "../../services/oss";
import * as evm from "../../services/evm";
import * as graphql from "../../services/graphql";
import * as suture from "../../services/suture";
import { downloadFile } from "../../utils/file-helper";
import { checkLogin } from "../../services/user";
import { uploadFiles } from "../../services/file-upload";
import webconfig from "../../webconfig";
import { formatPicUrl, formatterSizeStr } from "../../utils/formatter";
import FileDetail from "../../components/FileDetail";
const { Dragger } = Upload;
const { DirectoryTree } = Tree;

let treeSelectId = 0;
let lastSearchKey = "";
let timeout = null;
let isRenamingFolder = false;

let currTerritoryId = 0;
let territories = null;
let lastCid = 0;
let nav = [];

let choosedFileArr = [];
let choosedFilesTotalSize = 0;
let choosedFilesStorageSpace = 0;

let menuTimeout = null;
let menu2Timeout = null;

function Main({ className }) {
	const navigate = useNavigate();
	const [files, setFiles] = useState([]);
	const [dirs, setDirs] = useState([]);
	const [currDir, setCurrDir] = useState();
	const [navState, setNavState] = useState([]);
	const [nextNav, setNextNav] = useState();

	const [fileShowType, setFileShowType] = useState("block");

	const [keyword, setKeyword] = useState("");
	const [searchResult, setSearchResult] = useState([]);

	const [isLoading, setIsLoading] = useState(false);
	const [selectItem, setSelectItem] = useState();
	const [selectItems, setSelectItems] = useState([]);

	//Modal show
	const [createFolderBox, setCreateFolderBox] = useState(false);
	const [changeFolderBox, setChangeFolderBox] = useState(false);
	const [uploadBox, setUploadBox] = useState(false);
	const [uploadProps, setUploadProps] = useState();

	const [newFolderName, setNewFolderName] = useState("");
	const [folderTree, setFolderTree] = useState();

	const [choosedFiles, setChoosedFiles] = useState([]);
	const [showDetail, setShowDetail] = useState(null);

	const [syncing, setSyncing] = useState(false);
	const [showMenu, setShowMenu] = useState(false);
	const [contentMenu, setContentMenu] = useState({ display: "none", left: 0, top: 0 });

	const setNav = (arr) => {
		nav = arr;
		if (!nav || nav.length == 0) {
			lastCid = 0;
			currTerritoryId = 0;
		} else if (nav.length == 1) {
			lastCid = 0;
			currTerritoryId = nav[0].id;
		} else {
			lastCid = nav[nav.length - 1].id;
			currTerritoryId = nav[nav.length - 1].territoryId;
		}
		setNavState(arr);
	}

	const init = async () => {
		await getContainer();
	};
	useEffect(() => {
		treeSelectId = 0;
		lastSearchKey = "";
		timeout = null;
		isRenamingFolder = false;
		currTerritoryId = 0;
		lastCid = 0;
		nav = [];



		let isLogin = checkLogin(navigate);
		if (isLogin) {
			init();
		}
		window.refreshFileList = () => {
			getMyFiles();
		};
		return () => {
			window.refreshFileList = null;
		};
	}, []);

	//ajax post
	const getContainer = async () => {
		let fun = setIsLoading;
		if (currTerritoryId == 0 && territories) {
			setDirs(territories);
			fun = () => { };
			console.log('use cache');
		}
		// console.log('nav:', nav)
		// let ret = await suture.getContainer(nav.length < 2 ? 0 : parentId, currTerritoryId, setDirs, fun);
		let ret = await suture.getContainer(lastCid, currTerritoryId, setDirs, fun);
		if (ret.msg == 'ok' && ret.data && currTerritoryId == 0) {
			territories = ret.data;
		}
	};
	const newContainerSubmit = async () => {
		let ret;
		if (isRenamingFolder) {
			ret = await suture.renameContainer(selectItem, newFolderName, setIsLoading);
		} else {
			ret = await suture.newContainer(currDir, currTerritoryId, newFolderName, setIsLoading);
		}
		if (ret.msg != 'ok') return;
		setCreateFolderBox(false);
		setNewFolderName("");
		getMyFiles();
		getContainer();
		// getFolderTree();
	};
	const getMyFiles = async () => {
		// let ret = await graphql.getMyFiles(currTerritoryId, nav.length < 2 ? 0 : cid);
		let ret = await graphql.getMyFiles(currTerritoryId, lastCid);
		if (ret.msg != "ok") {
			return antdHelper.alertError(ret.msg);
		}
		console.log("getMyFiles", ret);
		setFiles(ret.data);
	};


	//btn event
	const onInput = (e, n) => {
		let v = e.target.value;
		if (n == "folderName") {
			setNewFolderName(v);
		}
	};
	const onSelectItem = item => {
		let i = selectItems.findIndex(t => t.id == item.id);
		// console.log(JSON.stringify(selectItems, null, 2), JSON.stringify(item, null, 2), i);
		if (i == -1) {
			setSelectItems(t => {
				t.push(item);
				return t;
			});
			setSelectItem(item);
		} else {
			setSelectItems(t => {
				t.splice(i, 1);
				if (t.length) {
					setSelectItem(t[t.length - 1]);
				} else {
					setSelectItem(null);
				}
				return t.slice(0, t.length);
			});
		}
	};
	const onStartDeleteFolderOrFile = async () => {
		let files = selectItems.filter(t => t.fid);
		let folders = selectItems.filter(t => !t.fid);
		let ret = await antdHelper.confirm(`Ara you sure to delete?`, 'Delete');
		if (!ret) return;
		let ret1 = { msg: "" }, ret2 = { msg: "" };
		if (files.length) {
			ret1 = await suture.fileDeletes(files, setIsLoading);
		}
		if (folders.length) {
			ret2 = await suture.deleteContainers(folders, setIsLoading);
		}
		if (ret1.msg == 'ok' || ret2.msg == 'ok') {
			getMyFiles();
			getContainer();
			setSelectItem(null);
			setSelectItems([]);
		}
	};
	const onStartNewOrRenameFolder = (isRename) => {
		isRenamingFolder = isRename;
		if (!isRename && nav.length == 0) {
			return navigate('/territory/new');
		}
		setCreateFolderBox(true);
	}
	const onShare = () => {
		if (!selectItem || !selectItem.shareLink) {
			return;
		}
		antdHelper.shareFile(window.location.origin + "/share/" + selectItem.shareLink);
	};

	//move file
	const onShowMoveFileBox = async () => {
		if (!selectItem) {
			return;
		}
		console.log({ selectItem });
		let ret = await suture.getContainerTree(false);
		if (ret.msg != 'ok') return;
		treeSelectId = 0;
		setFolderTree(ret.tree.filter(t => t.id == currTerritoryId));
		setChangeFolderBox(true);
	};
	const onTreeSelect = (keys, info) => {
		if (keys && keys.length) {
			treeSelectId = keys[0];
		}
		console.log("Trigger Select", keys[0]);
	};
	const onMoveFile = async () => {
		let ret = await suture.fileMove(selectItem, treeSelectId, currTerritoryId, setIsLoading);
		if (ret.msg != 'ok') {
			return;
		}
		getMyFiles();
		setChangeFolderBox(false);
	};

	//upload
	const onUploadSubmit = async () => {
		try {
			setIsLoading(true);
			if (!choosedFileArr.length) {
				return antdHelper.msgError("Please select a file.");
			}

			let territories = window.myTerritories;
			let currTerritory = territories.find(t => t.name == nav[0].name);
			let space = currTerritory.remainingSpace;
			if (space < choosedFilesStorageSpace) {
				return antdHelper.alertError(
					"The file size is larger than the remaining space."
				);
			}
			let containerId = nav.length < 2 ? 0 : currDir.id;
			let hasAuthor = window.isAuthor;
			if (!hasAuthor) {
				let tmp = await suture.authorize();
				if (tmp.msg == 'ok') {
					window.isAuthor = true;
				} else {
					return antdHelper.alertError(tmp.msg);
				}
			}
			await uploadFiles(currTerritoryId, containerId, currTerritory.name, choosedFileArr);
			setTimeout(function () {
				onHideUploadBox();
				if (window.setShowFileListBox) {
					window.setShowFileListBox(true);
				}
			}, 100);
		} catch (e) {
			console.log(e);
		} finally {
			setIsLoading(false);
		}
	};
	//nav event
	const onToRoot = async () => {
		setFiles([]);
		setNav([]);
		await getContainer();
	}
	const onOpenDir = async obj => {
		setIsLoading(true);
		setCurrDir(obj);
		setSelectItem(null);
		setSelectItems([]);
		setFiles([]);
		nav.push(obj);
		setNav(nav);
		setNextNav(null);
		setDirs([]);
		await getMyFiles();
		await getContainer();
		setIsLoading(false);
	};
	const onNavPre = async () => {
		if (!currTerritoryId) return;
		let obj = nav[nav.length - 1];
		setNextNav(obj);

		if (nav.length == 1) {
			onToRoot();
		} else {
			setSelectItem(null);
			setSelectItems([]);
			let obj2 = nav[nav.length - 2];
			setCurrDir(obj2);
			let nav2 = nav.slice(0, nav.length - 1);
			console.log(nav2);
			if (nav2.length > 1) {
				lastCid = obj2.id;
			} else {
				lastCid = 0;
			}
			setNav(nav2);
			getContainer();
			getMyFiles();
		}
	};
	const onNavNext = async () => {
		if (!nextNav) {
			return console.log("not a next floder");
		}
		if (nav.length == 0) {
			currTerritoryId = nextNav.id;
			lastCid = 0;
		} else {
			currTerritoryId = nextNav.territoryId;
			lastCid = nextNav.id;
		}
		setSelectItem(null);
		setSelectItems([]);
		setCurrDir(nextNav);

		nav.push(nextNav);
		setNav(nav);
		getMyFiles();
		getContainer();
		setNextNav(null);
	};
	const onNavClick = async obj => {
		let index = nav.findIndex(t => t.id == obj.id);
		if (index == -1 || index == nav.length - 1) {
			return;
		}
		lastCid = obj.id;
		setSelectItem(null);
		setSelectItems([]);
		setCurrDir(obj);
		setNextNav(null);
		// console.log('nav1', nav, index, nav.slice(0, index + 1))
		let nav2 = nav.slice(0, index + 1);
		setNav(nav2);
		// console.log('nav2', nav2)
		getContainer();
		getMyFiles();
	};
	const onShowRightMenu = (e, t) => {
		e.preventDefault();
		var left = e.clientX - 195;
		var top = e.clientY - 62;
		setSelectItems([t]);
		setSelectItem(t);
		clearTimeout(menu2Timeout);
		setContentMenu({
			display: "flex", left, top
		});
		onHideRightMenu(e, 1200);
	}
	const onMouseOverRightMenu = (e, t) => {
		clearTimeout(menu2Timeout);
	}
	const onHideRightMenu = (e, ms = 200) => {
		clearTimeout(menu2Timeout);
		menu2Timeout = setTimeout(function () {
			setContentMenu({
				display: "none"
			});
		}, ms);
	}
	const onRightMenuClick = (name) => {
		// return console.log(selectItem);
		switch (name) {
			case "open":
				if (selectItem.fid) {
					setShowDetail(selectItem);
				} else {
					onOpenDir();
				}
				break;
			case "download":
				onDownload();
				break;
			case "delete":
				onStartDeleteFolderOrFile();
				break;
			case "move":
				onShowMoveFileBox();
				break;
			case "rename":
				onStartNewOrRenameFolder(false);
				break;
			case "newfolder":
				onStartNewOrRenameFolder(true)
				break;
			case "share":
				onShare();
				break;
		}
		setContentMenu({
			display: "none"
		});
	}

	//search
	const onInputKeyword = async e => {
		let v = e.target.value.trim();
		setKeyword(v);
		clearTimeout(timeout);
		timeout = setTimeout(function () {
			onSearch();
		}, 500);
	};
	const onSearch = async e => {
		if (!keyword) {
			return;
		}
		if (keyword == lastSearchKey) return;
		lastSearchKey = keyword;
		let ret = await suture.fileSearch(keyword);
		console.log(ret);
		if (!ret || ret.msg != "ok") {
			return;
		}
		if (ret.data) {
			setSearchResult(ret.data);
		} else {
			setSearchResult([]);
		}
	};
	const renderTerritoryItem = (t, i) => {
		let prompt = "";
		let isDisaled = false;
		switch (t.state) {
			case "Active":
			case "OnConsignment":
				prompt = "Expire on " + t.deadlineTime.split('-').join('/');
				break;
			case "Frozen":
				prompt = "Expired";
				isDisaled = true;
				break;
			case "Expired":
				prompt = "Please reactive";
				isDisaled = true;
				break;
		}
		return (
			<div className="territory-item" key={i + "__" + t.key}>
				<Tooltip title={prompt}>
					<div className={isDisaled ? "territory-item-in territory-disabled" : "territory-item-in"} onDoubleClick={() => onOpenDir(t)}>
						{isDisaled ? <img src={process.env.PUBLIC_URL + "/img/filetype/disk-disabled.png"} /> : <img src={process.env.PUBLIC_URL + "/img/filetype/disk.png"} />}
						<div>
							<span className="name" title={t.name}>{t.name}</span>
							<span className="progress"><i style={{ width: t.usedSpacePer + '%' }}></i></span>
							<label title={"Locked " + t.lockedSpaceStr}>{t.remainingSpaceStr?.replace(" ", "")} free of {t.totalSpaceStr?.replace(" ", "")}</label>
						</div>
					</div>
				</Tooltip>
			</div>
		);
	};
	const renderFolderItem = (t, i) => {
		if (fileShowType == 'list') {
			return (
				<div onContextMenu={(e) => onShowRightMenu(e, t)} className={selectItems.find(a => t.id == a.id) ? "list-item list-curr" : "list-item list-uncurr"} key={t.id} onClick={() => onSelectItem(t)} onDoubleClick={() => onOpenDir(t)}>
					<span className="t1">
						<img width={16} height={16} src={process.env.PUBLIC_URL + "/img/filetype/folder.png"} />
						{t.name}
					</span>
					<span className="t2">folder</span>
					<span className="t3"></span>
				</div>
			);
		}
		return (
			<div onContextMenu={(e) => onShowRightMenu(e, t)} className={selectItems.find(a => t.id == a.id) ? "item curr" : "item uncurr"} key={t.id} onClick={() => onSelectItem(t)} onDoubleClick={cancelSelect}>
				<span></span>
				<img onDoubleClick={() => onOpenDir(t)} width={16} height={16} src={process.env.PUBLIC_URL + "/img/filetype/folder.png"} />
				<label onDoubleClick={() => onOpenDir(t)}>{t.name}</label>
			</div>
		);
	};
	const renderFileItem = (t, i) => {
		if (fileShowType == 'list') {
			return (
				<div onContextMenu={(e) => onShowRightMenu(e, t)} className={selectItems.find(a => t.id == a.id) ? "list-item list-curr" : "list-item list-uncurr"} key={i + "-" + t.id} title={t.title} onClick={() => onSelectItem(t)} onDoubleClick={() => setShowDetail(t)}>
					<span className="t1">
						<img width={16} height={16} src={process.env.PUBLIC_URL + "/img/filetype/" + t.fileTypeId + ".png"} />
						{t.title}
					</span>
					<span className="t2">{t.fileExt}</span>
					<span className="t3">{t.creationTime}</span>
				</div>
			);
		}
		return (
			<div onContextMenu={(e) => onShowRightMenu(e, t)} className={selectItems.find(a => t.id == a.id) ? "item curr" : "item uncurr"} key={i + "-" + t.id} title={t.title} onClick={() => onSelectItem(t)} onDoubleClick={() => setShowDetail(t)}>
				<span></span>
				<img width={16} height={16} src={process.env.PUBLIC_URL + "/img/filetype/" + t.fileTypeId + ".png"} />
				<label>{t.title}</label>
			</div>
		);
	};
	const onDownload = async () => {
		let files = selectItems.filter(t => t.fid);
		if (files.length == 0) {
			return;
		}
		for (let t of files) {
			let url = formatPicUrl(t.fid, t.fileExt);
			downloadFile(url, t.title);
		}
		setSelectItems([]);
	};
	const showUploadBox = (isFolder) => {
		onHideMenu();
		if (nav.length == 0) {
			return;
		}
		const uploadPropsNew = {
			name: "file",
			multiple: true,
			action: "",
			showUploadList: false,
			directory: isFolder,
			beforeUpload(file) {
				console.log(file);
				if (choosedFileArr.find(t => t.size == file.size && t.name == file.name)) {
					return false;
				}
				let sizeGB = file.size / (1024 * 1024 * 1024);
				if (sizeGB > webconfig.maxUploadSizeGB) {
					return antdHelper.alertError("Max " + webconfig.maxUploadSizeGB + " GB");
				}
				choosedFileArr.push(file);
				choosedFilesTotalSize = 0;
				choosedFilesStorageSpace = 0;
				for (let f of choosedFileArr) {
					let tmp = f.size;
					choosedFilesTotalSize += tmp;
					let mbu = 1024 * 1024;
					let mb = tmp / mbu;
					let count = Math.ceil(mb / 32);
					tmp = count * 96 * mbu;
					f.storageSpace = tmp;
					choosedFilesStorageSpace += tmp
				}
				setChoosedFiles(choosedFileArr.slice(0, choosedFileArr.length));
				return false;
			}
		};
		setUploadProps(uploadPropsNew);
		setUploadBox(true);
	};
	const onHideUploadBox = () => {
		setUploadBox(false);
		setChoosedFiles([]);
		choosedFileArr = [];
	}
	function cancelSelect() {
		window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
	}
	const refreshTerritory = async e => {
		setSyncing(true);
		await suture.territoryRefresh();
		await init();
		await getMyFiles();
		setSyncing(false);
	};
	const onRemoveChoosedFile = (i) => {
		choosedFileArr.splice(i, 1);
		setChoosedFiles(choosedFileArr.slice(0, choosedFileArr.length));
	}
	const onShowMenu = () => {
		if (nav.length == 0) {
			return;
		}
		clearTimeout(menuTimeout);
		setShowMenu(true);
	}
	const onHideMenu = () => {
		menuTimeout = setTimeout(() => {
			setShowMenu(false);
		}, 100);
	}

	return (
		<div className={className}>
			{showDetail ? <FileDetail className="file-detail" fileInfo={showDetail} fid={showDetail.fid} shareid={showDetail.shareid} onNavBack={() => setShowDetail(null)} /> : (
				<Spin spinning={isLoading}>
					<div className="btn-line">
						{showMenu && <div className="menu" onMouseOut={onHideMenu} onMouseOver={onShowMenu}>
							<label onClick={() => showUploadBox(false)}> + Files</label>
							<label onClick={() => showUploadBox(true)}> + Folder</label>
						</div>}
						<div className={nav.length == 0 ? "btn btn-disabled" : "btn btn-enable"} onClick={onShowMenu} onMouseOver={onShowMenu} onMouseOut={onHideMenu}>
							<img width={16} height={16} src={process.env.PUBLIC_URL + "/img/plus.png"} />
							<span className="label">Upload</span>
						</div>
						<div className={"btn btn-enable2"} onClick={() => onStartNewOrRenameFolder(false)}>
							<img width={16} height={16} src={process.env.PUBLIC_URL + "/img/folder.png"} />
							<span className="label" style={{ color: "#4E4E4E" }}>
								Create
							</span>
						</div>
						<div onClick={onShowMoveFileBox} className={selectItem && selectItems.length == 1 && selectItem.fid ? "btn btn-enable" : " btn btn-disabled"}>
							<DragOutlined />
						</div>
						<div onClick={onDownload} className={selectItems.find(t => t.fid) ? "btn btn-enable" : " btn btn-disabled"}>
							<ArrowDownOutlined />
						</div>
						<div onClick={onStartDeleteFolderOrFile} className={nav.length > 0 && selectItems.length > 0 ? "btn btn-enable" : " btn btn-disabled"}>
							<DeleteOutlined />
						</div>
						{
							selectItems.length == 1 && selectItem && !selectItem.fid ? <div onClick={() => onStartNewOrRenameFolder(true)} className="btn btn-enable"><EditOutlined /></div> :
								<div className="btn btn-disabled"><EditOutlined /></div>
						}
						<div onClick={onShare} className={selectItem && selectItems.length == 1 && selectItem.shareLink ? "btn btn-enable" : " btn btn-disabled"}>
							<ShareAltOutlined />
						</div>
						<div className="btn btn-sync" onClick={refreshTerritory}>
							<img className={syncing ? "rotate" : ""} width={16} height={16} src={process.env.PUBLIC_URL + "/img/refresh2.png"} />
							{
								syncing ? <span className="synchronizing">Synchronizing</span> : <span>Sync territories</span>
							}
						</div>
					</div>
					<div className="nav-line">
						{nav.length == 0 && navState.length < 2 ? (
							<div className="pre disable">
								<LeftOutlined className="licon" />
							</div>
						) : (
							<div className="pre enable" onClick={onNavPre}>
								<LeftOutlined className="licon" />
							</div>
						)}
						<div className={nextNav ? "next enable" : "next disable"} onClick={onNavNext}>
							<RightOutlined className="licon" />
						</div>
						<div className="nav">
							{/* <img width={14} style={{ cursor: "pointer" }} height={14} onClick={onToRoot} src={process.env.PUBLIC_URL + "/img/folder-color.png"} /> */}
							<span onClick={onToRoot} style={{ cursor: "pointer" }} ><DesktopOutlined /></span>
							{!keyword &&
								navState.map((n, i) => {
									return (
										<div key={n.id + "-" + i}>
											<span>
												<RightOutlined className="icon" />
											</span>
											<span className="nav-txt" onClick={() => onNavClick(n)}>
												{n.name}
											</span>
										</div>
									);
								})}
							{keyword ? (
								<div>
									<span>
										<RightOutlined className="icon" />
									</span>
									<span>Search： {keyword}</span>
									<label className="btn-reset" onClick={() => setKeyword("")}>
										X
									</label>
								</div>
							) : (
								""
							)}
						</div>
						<div className="search-box">
							<input value={keyword} onChange={onInputKeyword} onKeyUp={onInputKeyword} onInput={onInputKeyword} type="text" placeholder="Search file by Name" />
							<span onClick={onSearch}>
								<img width={16} height={16} src={process.env.PUBLIC_URL + "/img/search.svg"} />
							</span>
						</div>
					</div>
					<div className="content-menu" style={{ ...contentMenu }} onMouseOut={onHideRightMenu} onMouseOver={onMouseOverRightMenu}>
						<span className={selectItem ? "btn btn-enable" : " btn btn-disabled"} onClick={() => onRightMenuClick('open')}><AppstoreOutlined />Open</span>
						<span className={selectItem && selectItems.length == 1 && selectItem.fid ? "btn btn-enable" : " btn btn-disabled"} onClick={() => onRightMenuClick('move')}><DragOutlined />Move</span>
						<span className={selectItem && selectItems.length == 1 && selectItem.shareLink ? "btn btn-enable" : " btn btn-disabled"} onClick={() => onRightMenuClick('share')}><ShareAltOutlined />Share</span>
						<span className={selectItems.find(t => t.fid) ? "btn btn-enable" : " btn btn-disabled"} onClick={() => onRightMenuClick('download')}><ArrowDownOutlined />Download</span>
						<span className={selectItems.length == 1 && selectItem && !selectItem.fid ? "btn btn-enable" : " btn btn-disabled"} onClick={() => onRightMenuClick('rename')}><EditOutlined />Rename</span>
						<span className={selectItems.length > 0 ? "btn btn-enable" : " btn btn-disabled"} onClick={() => onRightMenuClick('delete')}><DeleteOutlined />Delete</span>
					</div>
					{navState.length > 0 && <div className="file-show-bar">
						<div className="file-show-type">
							<Radio.Group
								options={[
									{
										label: <UnorderedListOutlined />,
										value: 'list',
									},
									{
										label: <AppstoreOutlined />,
										value: 'block',
									}
								]}
								size="small"
								onChange={(e) => { setFileShowType(e.target.value) }}
								value={fileShowType}
								optionType="button"
								buttonStyle="solid"
							/>
						</div>
						{
							fileShowType == 'list' && <div className="file-box-bar-item">
								<span className="t1">Name</span>
								<span className="t2">Type</span>
								<span className="t3">Created</span>
							</div>
						}
					</div>}
					{keyword ? (
						<div className="file-box">
							{searchResult.length > 0 ? (
								searchResult.map(renderFileItem)
							) : (
								<Empty
									className="no-item"
									image={Empty.PRESENTED_IMAGE_SIMPLE}
									imageStyle={{
										height: 60
									}}
									description={'No file found where name like "' + keyword + '".'} key="empty1"></Empty>
							)}
						</div>
					) : (
						<div className="file-box">
							{files.length == 0 && dirs.length == 0 && (
								<Empty
									className="no-item"
									image={Empty.PRESENTED_IMAGE_SIMPLE}
									imageStyle={{
										height: 60
									}}
									description={nav.length == 0 ? "No territory" : "Empty folder"}>
									<Button type="primary" onClick={() => onStartNewOrRenameFolder(false)}>
										Create Now
									</Button>
								</Empty>
							)}
							{nav.length == 0 && dirs.map(renderTerritoryItem)}
							{nav.length > 0 && dirs.map(renderFolderItem)}
							{nav.length > 0 && files.map(renderFileItem)}
						</div>
					)}
				</Spin>)}
			<Modal width={800} title="" open={createFolderBox} destroyOnClose={true} footer={null} onCancel={() => { setCreateFolderBox(false); setNewFolderName("") }}>
				<Spin spinning={isLoading}>
					<div className="mypopu">
						<div className="title">{isRenamingFolder ? "Edit" : ""} folder name</div>
						<div className="con">
							<input type="text" value={newFolderName} onInput={e => onInput(e, "folderName")} className="text" placeholder="Maximum 20 characters" />
						</div>
						{/* <div style={{ width: 435, margin: "20px auto 0", color: "#888" }}>
							1. The name must be unique in the current account.
							<br />
							2. Its length must be between 3 ~ 63 characters.
							<br />
							3. Only lowercase letters, numbers, dots (.), and hyphens (-).
							<br />
							4. Must start and end with a letter or number.
							<br />
							5. Must not contain two adjacent periods.
							<br />
							6. Must not be formatted as an IP address.
						</div> */}
						<div className="footer">
							<span className="btn btn-primary" onClick={newContainerSubmit}>
								{isRenamingFolder ? "Confirm" : "Create"}
							</span>
							<span onClick={() => { setCreateFolderBox(false); setNewFolderName("") }} className="btn btn-default">
								Cancel
							</span>
						</div>
					</div>
				</Spin>
			</Modal>
			<Modal width={800} title="" open={changeFolderBox} footer={null} onCancel={() => setChangeFolderBox(false)}>
				<Spin spinning={isLoading}>
					<div className="mypopu">
						<div className="title">Move file to</div>
						<div className="con">
							<div className="tree-box">
								<DirectoryTree multiple defaultExpandAll onSelect={onTreeSelect} treeData={folderTree} />
							</div>
						</div>
						<div className="footer">
							<span className="btn btn-primary" onClick={onMoveFile}>
								Confirm
							</span>
							<span onClick={() => setChangeFolderBox(false)} className="btn btn-default">
								Cancel
							</span>
						</div>
					</div>
				</Spin>
			</Modal>
			<Modal width={800} title="" open={uploadBox} footer={null} onCancel={onHideUploadBox}>
				<div className="mypopu">
					<Spin spinning={isLoading}>
						<div className="con">
							<div className="upload-box">
								<Dragger {...uploadProps}>
									<div className="upload-box-txt">
										<span className="t1">Select {uploadProps?.directory ? "a folder" : "files"}</span>
										<span className="t2">Drag your file or folder here</span>
										<span className="t3">Max {webconfig.maxUploadSizeGB} GB</span>
									</div>
								</Dragger>
							</div>
						</div>
						{choosedFiles.length > 1 && <div className="btn-clear" onClick={() => { choosedFileArr = []; setChoosedFiles([]) }}><img width={16} height={16} src={process.env.PUBLIC_URL + "/img/menu-close.png"} /> Remove all</div>}
						{choosedFiles.map((t, i) => (<div className="sel-file-list" key={"f-" + i}>
							<div className="box">
								<div className="file-item">
									<span>File name</span>
									<span>{t.name}</span>
								</div>
								<div className="file-item">
									<span>File size</span>
									<span>{formatterSizeStr(t.size)}</span>
								</div>
								<div className="file-item">
									<span>Estimated storage space used:</span>
									<span>{formatterSizeStr(t.storageSpace)} &nbsp;
										<a href="https://docs.cess.cloud/core/readme/technical-highlight" target="_blank">
											<QuestionCircleOutlined style={{ cursor: 'pointer', color: 'blue' }} />
										</a>
									</span>
								</div>
							</div>
							<div className="btn" title="remove" onClick={() => onRemoveChoosedFile(i)}><img width={34} height={34} src={process.env.PUBLIC_URL + "/img/menu-close.png"} /></div>
						</div>))}
						<div className="tips-line">
							<div>Public Data</div>
							<i>All data uploaded to CESS is available to anyone who requests it using the correct FID. Do not store any private or sensitive information in an unencrypted form using CESS.</i>
						</div>
						<div className="footer">
							<span className="btn btn-primary" onClick={onUploadSubmit}>
								Upload
							</span>
							<span onClick={onHideUploadBox} className="btn btn-default">
								Cancel
							</span>
						</div>
					</Spin>
				</div>
			</Modal>
		</div>
	);
}

export default styled(Main)`
	display: block;
	.no-item {
		text-align: center;
		margin: 100px auto;
	}
	.link{
		cursor: pointer;
	}
	.btn-line {
		display: flex;
		clear: both;
		padding: 14px;
		height: 40px;
		flex-direction: row;
		position: relative;
		top:0;
		.menu{			
			background-color: #333333;
			color: #ffffff;
			display: flex;
			flex-direction: column;
			position: absolute;
			overflow: hidden;
			top: 45px;
			left: 14px;
			width: 99px;
			z-index: 1;
			border-radius: 10px;
			label{
				height: 30px;
				line-height: 30px;
				display: block;
				padding: 0 10px;
				font-size: 13px;
				cursor: pointer;
				&:hover{
					background-color: #444;
				}
			}
		}
		.btn {
			padding: 0 14px;
			height: 30px;
			line-height: 30px;
			text-align: center;
			color: #fff;
			border-radius: 8px;
			margin-right: 10px;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			.label {
				padding-left: 10px;
			}
		}
		.btn-enable {
			cursor: pointer;
			background-color: rgba(51, 51, 51, 1);
		}
		.btn-enable:hover {
			background-color: #333;
		}
		.btn-enable2 {
			cursor: pointer;
			background-color: rgba(240, 240, 240);
			color: #adadad;
			font-weight: weight;
		}
		.btn-disabled {
			cursor: not-allowed;
			background-color: rgba(240, 240, 240);
			color: #adadad;
			font-weight: weight;
		}
		.btn-sync{
			cursor: pointer;
			background-color: #f0f0f0;
			color: #4e4e4e;
			display: flex;
			flex-direction: row;
			justify-content: center;
			gap:10px;
			position: absolute;
			top: 15px;
			right: 2px;
			&:hover{
				background-color:#e1e0e0;
			}
			.synchronizing{
				color:#00d378;
			}
		}
	}
	.nav-line {
		display: flex;
		width: 100%;
		height: 56px;
		background-color: rgba(253, 253, 253, 1);
		border: 1px solid rgba(221, 221, 221, 1);
		flex-direction: row;
		align-items: center;
		line-height: 56px;
		border-left: none;
		border-right: none;
		.pre {
			width: 36px;
			height: 56px;
			margin-left: 10px;
			text-align: center;
			cursor: pointer;
		}
		.next {
			width: 36px;
			height: 56px;
			text-align: center;
			cursor: pointer;
			margin-right: 15px;
		}
		.enable {
			.licon {
				color: #000;
			}
		}
		.disable .licon {
			color: #aaa;
		}
		.nav {
			flex: 1;
			height: 36px;
			line-height: 36px;
			background-color: #fff;
			border: 1px solid rgba(221, 221, 221, 1);
			border-radius: 8px;
			padding: 0 10px;
			display: flex;
			flex-direction: row;
			align-items: center;
			img {
				margin: 0 4px;
			}
			span {
				margin: 0 5px;
			}
			.nav-txt {
				cursor: pointer;
			}
			.icon {
				width: 6px;
				height: 6px;
			}
			.btn-reset {
				margin-left: 10px;
				background-color: #aaaaaa5e;
				line-height: 16px;
				width: 16px;
				border-radius: 16px;
				text-align: center;
				height: 16px;
				display: inline-block;
				cursor: pointer;
				color: #252525;
				font-size: 10px;
			}
			.btn-reset:hover {
				background-color: #eee;
			}
		}
		.search-box {
			width: 300px;
			height: 36px;
			line-height: 36px;
			background-color: #fff;
			border: 1px solid rgba(221, 221, 221, 1);
			margin: 0 10px;
			border-radius: 8px;
			padding: 0 10px;
			display: flex;
			flex-direction: row;
			align-items: center;
			input {
				width: 90%;
				height: 36px;
				background-color: transparent;
				outline: none;
				border: none;
				padding: 0;
				margin: 0;
			}
			span {
				width: 10%;
				height: 36px;
				text-align: center;
				cursor: pointer;
				img {
					margin: 10px;
				}
			}
		}
	}
	.content-menu{
		width: 200px;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		box-shadow: 0 0 9px #00000054;
		border-radius: 4px;
		position: absolute;
		top:100px;
		left:100px;
		z-index: 99;
		overflow: hidden;
		.btn{
			display: flex;
			flex-direction: row;
			gap:15px;
			align-items: center;
			height:40px;
			line-height: 40px;
			border-bottom: 1px solid #eee;			
			font-size:14px;
			padding:0 15px;
			cursor: default;			
		}
		.btn-disabled{
			color:#aaa;
		}
		.btn-enable{
			color:#000;
			&:hover{
				background-color: #f2f2f2;
			}
		}
	}
	.file-show-bar{
		width: 100%;
		position: relative;
		top:0;
		.file-show-type{
			position: absolute;
			top:3px;
			right:3px;
		}
		.file-box-bar-item{
			width: 100%;
			height: 30px;
			display: flex;
			flex-direction: row;
			-webkit-box-align: center;
			align-items: center;
			border-bottom: 1px solid #eee;
			span{
				text-indent: 10px;
			}
			.t1{
				width: 50%;
			}
			.t2{
				width: 20%;
				border-left: 1px solid #eee;
			}
			.t3{
				width: 30%;
				border-left: 1px solid #eee;
			}
		}
	}
	.file-box {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		padding: 20px;		
		.territory-item{	
			width: 308px;
			display: block;
			float: left;
			&-in{
				display: flex;
				flex-direction: row;
				gap:20px;
				align-items: center;
				padding: 10px;
				border-radius: 5px;		
				transition: all .2s;
				margin: 10px;		
				&:hover{				
					box-shadow: 0 0 19px #00000057;			
				}
				img{
					width:50px;
					height:50px;
				}	
				div{
					flex:1;
					display: flex;
					flex-direction: column;
					gap:2px;		
					overflow: hidden;			
					.name{
						font-size:15px;
					}
					.progress{
						width:100%;
						height:14px;
						border-radius: 14px;
						background-color: #eeeeee;
						i{
							height: 14px;
							display: block;
							overflow: hidden;
							border-radius: 14px;
							background-color: #0068ff;
						}
					}
					label{
						color:#737373;
					}
				}	
			}
			.territory-disabled{
				opacity: 0.5;
			}
		}
		.item {
			width: 120px;
			height: 120px;
			display: flex;
			flex-direction: column;
			text-align: center;
			align-items: center;
			justify-content: center;
			border-radius: 10px;
			position: relative;
			border: 1px solid #fff;
			margin: 4px 6px;
			top: 0;
			img {
				width: 50px;
				height: 50px;
				margin-top: 8px;
			}
			label {
				width: 100px;
				height: 20px;
				line-height: 20px;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				margin-top: 14px;
			}
			span {
				width: 30px;
				height: 30px;
				display: block;
				overflow: hidden;
				position: absolute;
				top: 0px;
				left: 0px;
				background-repeat: no-repeat;
				background-position: center;
				background-size: 17px;
				cursor: pointer;
			}
		}
		.list-item{
			width: 98%;
			height: 34px;
			display: flex;
			flex-direction: row;
			-webkit-box-align: center;
			align-items: center;
			margin:2px 0;
			padding:0 1%;
			border: 1px solid #fff;
			span{
				text-indent: 2px;
			}
			.t1{
				width: 50%;
				display: flex;
				flex-direction: row;
				gap:4px;
				align-items: center;
			}
			.t2{
				width: 20%;
			}
			.t3{
				width: 30%;
				color:#aaa;
			}
		}
		.uncurr:hover {
			background-color: #f2f2f2;
			span {
				background-image: url(/img/check-gray.svg);
			}
		}
		.curr {
			background-color: #f2f2f2;
			border: 1px solid rgba(51, 51, 51, 1);
			span {
				background-image: url(/img/check.svg);
			}
		}
		.list-uncurr:hover {
			background-color: #e3fbff;
		}
		.list-curr {
			background-color: #cce8fe;
			border: 1px solid #adcce8;
		}
	}
`;
